package br.unifor.cct.mia.coevolution.memory;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class MemoryBuffer {

	public static final String BUFFER_SEMAPHORE = "S";
	public static int BUFFER_SIZE = 5;
	private List buffer;
	
	public MemoryBuffer() {
		buffer = new ArrayList();
	}
	
	public synchronized boolean add(SharedMemory memory) {
		boolean added = false;
		
		if ( buffer.size() < BUFFER_SIZE ) {
			buffer.add(memory);
			added = true;
		}
		else {
			double minValue = memory.getFitness();
			SharedMemory minMemory = null;
			
			Iterator iter = buffer.iterator();			
			while ( iter.hasNext() ) {
				SharedMemory mem = (SharedMemory)iter.next();
				
				if ( mem.getFitness() < minValue ) {
					minMemory = mem;
					minValue = mem.getFitness();
				}
			}
			
			if ( minMemory != null ) {
				buffer.remove(minMemory);
				buffer.add(memory);
				added = true;
			}
		}
		
		return added;
	}
	
	public synchronized SharedMemory getBestMemory() {
		if ( buffer.size() == 0 ) return null;
		
		SharedMemory best = (SharedMemory)buffer.get(0);		
		Iterator iter = buffer.iterator();			
		while ( iter.hasNext() ) {
			SharedMemory mem = (SharedMemory)iter.next();
			
			if ( mem.getFitness() > best.getFitness() ) {
				best = mem;
			}
		}
		
		return best;		
	}
	
	public synchronized List getMemoryElements() {
		return buffer;
	}
	
	public void clean() {
		buffer = new ArrayList();
	}
	
	public void setBufferSize(int size) {
		this.BUFFER_SIZE = size;
	}

}
